package com.example.weibo_suhuanzhen.activities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager2.widget.ViewPager2;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.weibo_suhuanzhen.adapters.DetailPagerAdapter;
import com.example.weibo_suhuanzhen.R;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class DetailActivity extends AppCompatActivity {
    private static final int REQUEST_PERMISSION_CODE = 1001;
    private ImageView avatar;
    private TextView username;
    private ViewPager2 viewPager2;
    private List<String> imageUrls;
    private TextView indexTextView;
    private TextView download;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        avatar = findViewById(R.id.avatar_in_detail);
        username = findViewById(R.id.username_in_detail);
        viewPager2 = findViewById(R.id.detail_pager);
        indexTextView = findViewById(R.id.index);
        download = findViewById(R.id.download);

        Intent intent = getIntent();
        String usernameStr = intent.getStringExtra("username");
        String avatarUrl = intent.getStringExtra("avatar");
        imageUrls = intent.getStringArrayListExtra("images");
        position = intent.getIntExtra("position", 1);

        username.setText(usernameStr);
        Glide.with(this).load(avatarUrl).transform(new CircleCrop()).into(avatar);

        // Set ViewPager2
        DetailPagerAdapter adapter = new DetailPagerAdapter(this, imageUrls);
        viewPager2.setAdapter(adapter);

        viewPager2.setCurrentItem(position, false);

        // 滑动时更新位置
        updateIndexText(position);
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                updateIndexText(position);
            }
        });

        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(DetailActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求权限
                    ActivityCompat.requestPermissions(DetailActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_PERMISSION_CODE);
                } else {
                    // 已经有权限，直接下载图片
                    int currentItem = viewPager2.getCurrentItem();
                    String imageUrl = imageUrls.get(currentItem);
                    new DownloadImageTask(DetailActivity.this).execute(imageUrl);
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，继续下载图片
                int currentItem = viewPager2.getCurrentItem();
                String imageUrl = imageUrls.get(currentItem);
                new DownloadImageTask(DetailActivity.this).execute(imageUrl);
            } else {

                // 权限被拒绝
                jumpToSetting();
                Toast.makeText(this.getApplicationContext(), "需要存储权限才能下载图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void updateIndexText(int position) {
        String indexText = (position + 1) + "/" + imageUrls.size();
        indexTextView.setText(indexText);
    }

    private static class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        private Context context;

        public DownloadImageTask(Context context) {
            this.context = context.getApplicationContext();
        }

        @Override
        protected Bitmap doInBackground(String... urls) {
            String url = urls[0];
            Bitmap bitmap = null;
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.connect();
                bitmap = BitmapFactory.decodeStream(connection.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                saveImageToGallery(context, result);
            } else {
                Toast.makeText(context.getApplicationContext(), "下载图片失败", Toast.LENGTH_SHORT).show();
            }
        }

        private void saveImageToGallery(Context context, Bitmap bitmap) {
            ContentResolver resolver = context.getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "image_" + System.currentTimeMillis() + ".jpg");
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

            Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

            try (OutputStream outputStream = resolver.openOutputStream(imageUri)) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                Toast.makeText(context.getApplicationContext(), "图片已保存到相册", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(context.getApplicationContext(), "保存图片失败", Toast.LENGTH_SHORT).show();
            }
        }

    }
    private void jumpToSetting(){
        Intent intent=new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri=Uri.fromParts("package",getPackageName(),null);
        intent.setData(uri);
        startActivity(intent);
    }
}
